import random

from django import http

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from meiduo_mall.libs.captcha.captcha import captcha
from meiduo_mall.utils.response_code import RET
from verifications import constants


class ImageCodeView(View):
    def get(self, request, image_code_id):
        text, image_data = captcha.generate_captcha()

        # 保存输入的验证码
        redis_conn = get_redis_connection("code")
        redis_conn.setex("image_code_%s" % image_code_id, 300, text)

        return http.HttpResponse(image_data, content_type="image/png")


class SmsCodeView(View):
    def get(self, request, mobile):
        # 获取参数
        image_code = request.GET.get("image_code")
        image_code_id = request.GET.get("image_code_id")
        # 校验参数
        if not all([image_code, image_code_id]):
            return http.JsonResponse({"errmsg": "参数不全", "code": RET.PARAMERR})
        # 判断是否过期
        redis_conn = get_redis_connection("code")
        redis_image_code = redis_conn.get("image_code_%s" % image_code_id)
        if not redis_image_code:
            return http.JsonResponse({"errmsg": "图片验证码过期", "code": RET.NODATA})
        # 删除
        redis_conn.delete("image_code_%s" % image_code_id)
        # 正确性
        if image_code.lower() != redis_image_code.decode().lower():
            return http.JsonResponse({"errmsg": "验证码输入错误", "code": RET.DATAERR})
        # 判断是否频繁发送
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            return http.JsonResponse({"errmsg": "频繁发送短信", "code": RET.SMSCODERR})
        # 发送短信
        sms_code = "%06d" % random.randint(0, 999999)

        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code, constants.REDIS_SMS_CODE_EXPIRES / 60)
        # 保存到redis中
        pipeline = redis_conn.pipeline()
        pipeline.setex("sms_code_%s" % mobile, constants.REDIS_SMS_CODE_EXPIRES, sms_code)
        pipeline.setex("send_flag_%s" % mobile, constants.REDIS_SEND_FLAG_EXPIRES, 1)
        pipeline.execute()
        # 返回响应
        return http.JsonResponse({"errmsg": "发送成功", "code": RET.OK})
